<?php
/**
 * Created by PhpStorm.
 * User: front
 * Date: 2018/8/3
 * Time: 16:39
 */

namespace App\Services;

use App\Exceptions\ApiException;
use App\Models\ActivityConfig;
use App\Models\FriendModel;
use App\Models\FriendUser;
use App\Models\Media;
use App\Models\MediaComment;
use App\Models\MediaHistory;
use App\Models\MediaLike;
use App\Models\MediaLikeLog;
use App\Models\MediaLikeStatic;
use App\Models\MediaRecommend;
use App\Models\MediaStar;
use App\Models\MobileMark;
use App\Models\User;
use App\Models\UserDynamicList;
use App\Models\UserTicket;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use App\Services\Pusher;
use Illuminate\Support\Facades\Redis;
use Yankewei\LaravelSensitive\Facades\Sensitive;
use App\Models\JpushMobile;
use App\Jobs\PushQueue;

class MediaService
{

    /*
     * 当前用户发布最新视频   ---待作废
     * */
    public static function userNewMedia($view_user_ticket)
    {
        $ClientSource = Input::get('ClientSource',3);

        $fields = ['id','title', 'description','media','comments','star','like','is_like','uid','created_at','address','location','cover','video_length','share'];
        $user = $view_user_ticket->_user()->first();
        $user_latest_media = Media::where([['uid', '=', $view_user_ticket->uid], ['status', '=', 1], ['is_delete', 0]])->orderBy('id', 'desc')->first($fields);
        if ($user_latest_media) {
            $user_latest_media->protected_avatar = !empty($user_latest_media->_user->avatar) ? $user_latest_media->_user->avatar : '';
            $user_latest_media->protected_media = !empty($user_latest_media->media) ? $user_latest_media->media : '';

            $user_latest_media->username = $user_latest_media->_user->name;
            $user_latest_media->avatar = !empty($user_latest_media->_user->avatar) ? getSignUrl($user_latest_media->_user->avatar) : '';
            $user_latest_media->media = getSignUrl($user_latest_media->media);
            $user_latest_media->cover = getSignUrl($user_latest_media->cover);
            $user_latest_media->is_star = $user->_mediaStars()->where('media_id', $user_latest_media->id)->first() ? 1 : 0;
            $media_like = D('media_like')->where([['media_id', $user_latest_media->id], ['uid', $user->id]])->first();
            $user_latest_media->is_like = $media_like && $media_like->is_delete == '0' ? 1 : 0;
            unset($user_latest_media->_user);

            $user_latest_media->is_friend = 0;
            $user_latest_media->is_attention = 0;
        }

        return $user_latest_media;
    }

    /*
     * 获取资讯详情
     * */
    public static function getDataOfMediaDetail($request)
    {
        $media_id = IT('media_id', true, '未知视频资讯', 10100);
        $ticket = $request->input('ticket');
        $ClientSource = $request->input('ClientSource');

        $media = Media::where('id', $media_id)->first();
        if (!$media)
            EE('未找到响应内容', 0, 10051);
        if ($media->is_delete == 1)
            EE('该视频已删除', 0, 10144);

        $user_ticket = UserTicket::where([ ['status','=',1],['ticket','=',$ticket] ])->first();
        // $view_user_ticket = UserTicket::where([['ticket',$request->input('ticket')],['client_source',$request->input('ClientSource')], ['status',1]])->first();
        // 记录浏览记录    --抽出来队列-队列
        if(!empty($user_ticket))
            MediaHistory::addMediaHistory($media_id, $ticket);

        // 亲友圈类型视频
        if($media->is_private == '2'){
            if(empty($user_ticket))
                EE('用户未登录不能查看亲友圈视频', 0, 10145);

            $friend_rows_id = FriendModel::getRowsObj([['uid', '=', $user_ticket->uid],['friend_uid', '=', $media->uid], ['status', '=', '1']], 'id');
            if(empty($friend_rows_id) && $user_ticket->uid != $media->uid)
                EE('您还不是亲友，不能查看该视频', 0, 10146);
        }

        $data = [];
        $data['comments_total'] = $media->comments; // 动态数据
        $data['title'] = $media->title;
        $data['description'] = $media->title;

        $data['avatar'] =  (isset($media->_user ) && !empty($media->_user->avatar) ? getSignUrl($media->_user->avatar) : "");
        $data['username'] = (isset($media->_user ) && !empty($media->_user->name) ? $media->_user->name : "");
        $data['cover'] = getSignUrl($media->cover);
        //  $data['viplevel'] = $media->_user->vip_level;
        $data['uid'] = (isset($media->_user ) && !empty($media->_user->id) ? $media->_user->id : "");
        // $data['vipname'] = User::getVipStr($media->_user->vip_level);
        $data['created_at'] = $media->created_at->format('Y-m-d H:i:s');
        $data['content'] = $media->content;
        $data['type'] = $media->type;
        $data['media'] = getSignUrl($media->media);
        $data['is_author_star'] = 1;
        $data['address'] = $media->location;
        $data['location'] = $media->location;
        $data['video_length'] = $media->video_length;
        $data['is_friend'] = 0;
        $data['is_attention'] = 0;
        $data['star'] = $media->star;
        $data['share'] = $media->share;
        $data['like'] = $media->like;
        $data['id'] = $media->id;
        $media_users_arr = User::get_user_rows_arr($media->uid);
        $data['protected_avatar'] = isset($media_users_arr['avatar']) ? $media_users_arr['avatar'] : '';
        $data['protected_media'] = $media->media;
        $data['is_forward'] = $media->is_forward;
        $data['forward_name'] = null;
        $data['forward_content'] = null;
        $data['is_screen_recording'] = $media->is_screen_recording;
        $data['sex'] = $media_users_arr['sex'];
        $data['is_star'] = 0;
        $data['is_like'] = 0;

        // 是否收藏
        if(!empty($user_ticket)){
            $user = $user_ticket->_user()->first();
            $data['is_star'] = ($user && $user->_mediaStars()->where('media_id',$media->id)->first()) ? 1 : 0;

            // 是否点赞
            if ($user)
                $media_like = D('media_like')->where([ ['media_id', $media->id], ['uid', $user->id] ])->first();
            $data['is_like'] = (isset($media_like)  && !empty($media_like) && $media_like->is_delete == '0') ? 1 : 0;
        }

        // 获取视频评论
        $commentsList = self::getMediaCommentList($request);
        $data['comments'] = $commentsList;

        $star = 0 ; //关注状态：0未关注，1已关注
        if ($user_ticket)
        {
            $user = $user_ticket->_user()->first();
            if ($user)
            {
                if ( MediaStar::where([ ['uid','=',$user->id],['media_id','=',$media->id],['status','=',1] ])->first() ){
                    $data['is_media_star'] = 1; //已收藏该资讯
                }else {
                    $data['is_media_star'] = 0;      //未收藏该资讯
                }
                $star = D('friend_user')->where([['uid', $user->id], ['friend_id', $media->uid], ['status', 1]])->first() ? 1 : 0 ;
                if ($user->id == $media->uid) {
                    $data['is_author_star'] = -1;
                    $star = -1;
                }
            }
        }

        // 是否亲友
        if ($user_ticket && $user_ticket->uid != $media->uid){
            // 亲友
            $friend_rows_id = FriendModel::getRowsObj([['uid', '=', $user_ticket->uid],['friend_uid', '=', $media->uid], ['status', '=', '1']], 'id');
            if(!empty($friend_rows_id))
                $data['is_friend'] = 1;
            if(!empty($star))
                $data['is_attention'] = 1;
        }

        foreach ($data['comments']['list']  as $k=>&$v) {
            $v->is_allow_delete = 0;                                //查看不是自己的不允许删除
            if (isset($user) && $v->uid == $user->id){             //如果是要查看其他用户主页,且该用户已登录,但查看的是自己的信息
                $v->is_allow_delete = 1;                            //自己查看自己的允许删除
            }
        }
        $media->pv = $media->pv+1;
        $media->save();
        return $data;
    }

    /*
     * 视频评论列表
     * */
    public static function getMediaCommentList($request)
    {
        $media_id =  $request->input('media_id');
        $action_type =  $request->input('action_type', 2);
        $start_comment_id = $request->input('start_comment_id');
        $pagesize =  $request->input('pagesize') ?? config('params')['pagesize'];

        $comment = new MediaComment();
        // 默认下拉
        $order_by = ' mc.id desc';
        // 常规分页查询
        if(empty($start_comment_id)){
            $sql = 'SELECT mc.`id`,mc.`content`,mc.`created_at`,mc.`uid`,u.`name`,u.`avatar`, up.`id` as reply_uid,up.`name` as reply_name,mc.type FROM '.$comment->getTable().' as mc '
                .' LEFT JOIN `users` as u ON mc.uid=u.id'
                .' LEFT JOIN `users` as up ON mc.reply_uid=up.id'
                .' WHERE mc.`media_id`=? AND mc.`status`=1 AND mc.`is_delete`=0'
                .' ORDER BY '.$order_by.' LIMIT ?';
            $data = DB::select($sql, [$media_id, $pagesize]);
        }else{
            $sql = 'SELECT mc.`id`,mc.`content`,mc.`created_at`,mc.`uid`,u.`name`,u.`avatar`, up.`id` as reply_uid,up.`name` as reply_name,mc.type FROM '.$comment->getTable().' as mc '
                .' LEFT JOIN `users` as u ON mc.uid=u.id'
                .' LEFT JOIN `users` as up ON mc.reply_uid=up.id'
                .' WHERE mc.`media_id`=? AND mc.`status`=1 AND mc.`is_delete`=0 AND mc.`id`<=?'
                .' ORDER BY '.$order_by.' LIMIT ?';
            // 2：向上滑动 是向下翻页
            if($action_type == 1){
                $order_by = ' mc.id asc';
                $sql = 'SELECT mc.`id`,mc.`content`,mc.`created_at`,mc.`uid`,u.`name`,u.`avatar`, up.`id` as reply_uid,up.`name` as reply_name,mc.type FROM '.$comment->getTable().' as mc '
                    .' LEFT JOIN `users` as u ON mc.uid=u.id'
                    .' LEFT JOIN `users` as up ON mc.reply_uid=up.id'
                    .' WHERE mc.`media_id`=? AND mc.`status`=1 AND mc.`is_delete`=0 AND mc.`id`>=?'
                    .' ORDER BY '.$order_by.' LIMIT ?';
            }
            $data = DB::select($sql, [$media_id, $start_comment_id, $pagesize]);
        }
        rsort($data);

        $comments = Media::where([['id', '=', $media_id]])->value('comments');
        // 查询视频评论的最后一页
        $next_page = empty($data) ? 0 : 1;
        $media_comment_min_id = self::mediaCommentMinId($media_id);
        foreach ($data as &$value){
            if($media_comment_min_id == $value->id)
                $next_page = 0;
            $value->avatar = getSignUrl($value->avatar);
        }

        return ['media_id'=>$media_id, 'next_page'=>$next_page, 'comments_total'=>$comments, 'list'=>$data];
    }

    /*
     * 删除评论
     * $comment_id 评论/回复内容id
     * */
    public static function delComment($uid, $comment_id)
    {
        // 获取视频地址
        $media_comment = D('media_comment')->where([['id','=',$comment_id]])->first();
        if(empty($media_comment))
            EE('未知评论内容或已删除', 0, 10147);
        if($uid != $media_comment->uid)
            EE('不能删除其他人评论', 0, 10148);
        if($media_comment->status == '0' or $media_comment->is_delete == '1')
            return true;

        $media_comment_model = new MediaComment();
        $sql = "select id from ".$media_comment_model->getTable()." where media_id={$media_comment->media_id}  and status=1 and is_delete=0 and relation_id like ('%,{$media_comment->id},%')";
        $reply_comment_list = DB::select($sql);

        $temp_arr = [];
        // 评论回复的数量
        $media_comment_count = 1;
        if(!empty($reply_comment_list)){
            $media_comment_count = $media_comment_count+count($reply_comment_list);
            foreach ($reply_comment_list as $value){
                $temp_arr[] = $value->id;
            }
        }
        $temp_arr[] = $media_comment->id;

        DB::beginTransaction();
        // 设置无效  且删除
        $sql = "update ".$media_comment_model->getTable()." set status=0, is_delete=1 where id in (".implode(',', $temp_arr).")";
        $update = DB::update($sql);
        if(empty($update)) {
            DB::rollBack();
            EE('删除评论失败', 0, 10149);
        }

        $userDynamic = new UserDynamicList();
        $sql = "update ".$userDynamic->getTable()." set status=0 where operation_id in (".implode(',', $temp_arr).") ";
        $update = DB::update($sql);
        if(empty($update)) {
            DB::rollBack();
            EE('删除动态失败', 0, 10150);
        }

        // 更新回复数量
        $update = D('media')->where([['id', '=', $media_comment->media_id]])->decrement('comments', ($media_comment_count));
        if(!$update) {
            DB::rollBack();
            EE('更新回复数量失败', 0, 10155);
        }

        // 转发视频类型评论删除，需要删除转发的视频
        if($media_comment->type == 1) {
            $media_info = D('media')->where([['forward_id','=',$comment_id],['is_forward','=',1],['is_delete','=',0]])->first();
            if($media_info) {
                $update = D('media')->where([['forward_id','=',$comment_id],['is_forward','=',1],['is_delete','=',0]])->update(['is_delete'=>1]);
                if(!$update) {
                    DB::rollBack();
                    EE('删除转发视频失败', 0, 10156);
                }
            }

        }

        DB::commit();
        return true;
    }

    /*
     * 添加视频评论 / 回复评论
     * */
    public static function add_media_comments($request, $uid)
    {
        $media_id = $request->input('media_id');
        $content = $request->input('content');
        $type = $request->input('type');
        $media_comments_id = $request->input('media_comments_id');
        $parent_id = 0;
        $reply_uid = 0;
        $relation_id = '';

        // 敏感词过滤
        $interference = ['&', '*'];
        $filename = config_path().'/sensitiveword.txt'; //每个敏感词独占一行
        Sensitive::interference($interference); //添加干扰因子
        Sensitive::addwords($filename); //需要过滤的敏感词
        $filter_content = Sensitive::filter($content);
        /*
         * if ( strcmp($filter_content,$content)!=0 && config('basic.sensitive_data_filter')=='prevent' ) { //存在敏感词
            throw new ApiException('内容包含敏感词',0);
        }*/
        $filter_content = Filter::init($filter_content);

        $reply_name = "";
        // 检验父级评论是否存在
        if($type == 2 ){
            if(empty($media_comments_id))
                EE('您要回复的资讯评论不存在，无法回复', 0, 10151);
            $prentMediaComment = MediaComment::where([['id', '=', $media_comments_id], ['is_delete', '=', '0']])->first();
            if(empty($prentMediaComment))
                EE('您要回复的资讯评论不存在，无法回复', 0, 10151);

            $reply_name = $prentMediaComment->_user->name;
            $parent_id = $media_comments_id;
            $reply_uid = $prentMediaComment->uid;

            $relation_id = ','.$media_comments_id.',';
            if(!empty($prentMediaComment->relation_id)){
                $relation_id = $prentMediaComment->relation_id.$media_comments_id.',';
            }

        }

        // 累加评论次数
        $media = self::checkMedia($media_id);
        if (!$media)
            EE('您想要评论的资讯不存在，无法评论', 0, 10152);
        elseif ($media->is_delete)
            EE('您想要评论的资讯已被删除，无法评论', 0, 10153);

        $media->comments = $media->comments + 1;
        $media->save();

        // 添加评论/回复内容
        $comment = new MediaComment;
        $comment->uid = $uid;
        $comment->reply_uid = $reply_uid;
        $comment->media_id =  $media_id;
        $comment->parent_id = $parent_id;
        $comment->relation_id = $relation_id;
        $comment->content = $filter_content;

        // 添加评论
        $comment->save();
        if(!$comment)
            return ['status'=>'error', 'message_code'=>10154, 'message'=>'评论异常'];

        // 用户动态 --------可以抽出来队列 处理
        $UserDynamicListModel = new UserDynamicList();
        $UserDynamicListModel->uid = ($type == 1) ? $media->uid : $comment->reply_uid;
        $UserDynamicListModel->type = $type;
        $UserDynamicListModel->operation_id = $comment->id;
        $UserDynamicListModel->parent_id = $parent_id;
        $UserDynamicListModel->option_uid = $uid;
        $UserDynamicListModel->media_id = $media->id;
        $UserDynamicListModel->option_other = $media->cover;
        $UserDynamicListModel->option_content = $filter_content;
        $UserDynamicListModel->create_time = time();
        $UserDynamicListModel->update_time = time();
        if(!$UserDynamicListModel->save())
            return ['status'=>'error', 'message_code'=>10154, 'message'=>'添加动态异常'];

        // 被回复的用户名字
        $comment->reply_name = $reply_name;
        return ['status'=>'success', 'message_code'=>10156, 'message'=>'评论成功', 'data'=>['media_info'=>$media, 'media_comments'=>$comment]];
    }

    /*
     * 校验视频是否存在
     * */
    public static function checkMedia($media_id)
    {
        $rows = Media::find($media_id);
        if(empty($rows))
            return false;
        return $rows;
    }

    /*
     * 设置/获取 视频的有效最小评论id 缓存
     * */
    public static function mediaCommentMinId($media_id)
    {
        if(!empty(Redis::get('media_comment_min_id:'.$media_id)))
            return Redis::get('media_comment_min_id:'.$media_id);

        $media_comment_min_id = D('media_comment')->where([['media_id', '=', $media_id], ['status', '=', '1'],['is_delete', '=', '0']])->min('id');
        Redis::	SETEX('media_comment_min_id:'.$media_id, rand(3600, 7200), $media_comment_min_id);

        return $media_comment_min_id;
    }
    /*
     * 改变动态
     * */
    public static function changeDynamic($where, $update=[])
    {
        $update = UserDynamicList::where($where)->update($update);
        if($update)
            return true;
        return false;
    }

    public static function mediaList($uid,$page,$rows)
    {
        // 获取条件
        $select = array(
            'media.id','media.title', 'media.description','media.comments','media.star','media.media','media.share','media.like',
            'media.cover','media.address','media.location','media_like.id as is_like','media.uid', 'media.created_at',
            'users.name','users.avatar','media_star.created_at','users.sex'
        );
        $where = array(
            ['media_star.uid','=',$uid],
            ['media_star.status','=',1],
            ['media.status','=',1],
            ['media.is_delete','=',0]
        );
        $order = 'media_star.sorts desc,media_star.id desc,media.sorts desc,media.id desc';
        $data = D('media_star')
            ->join('media','media_star.media_id','=','media.id')
            ->join('users','media.uid','=','users.id')
            ->leftJoin('media_like', function($join) use($uid){
                $join->on('media.id', '=', 'media_like.media_id')->where('media_like.uid', $uid);
            })
            ->where($where)
            ->orderByRaw($order)
            ->offset($page)
            ->limit($rows)
            ->get($select);
        return  $data;
    }

    /*
     * 2.1 待作废
     * */
    public static function handleDataOfMediaList(&$media_list, $view_user_ticket)
    {
        $is_login = $view_user_ticket && $view_user_ticket->_user()->first();
        $user = $is_login ? $view_user_ticket->_user()->first() : null;

        if(isset($media_list)){
            foreach ($media_list as &$media){
                $media->protected_avatar = isset($media->_user->avatar) ? ($media->_user->avatar) : (isset($media->avatar) ? ($media->avatar) : '');;
                $media->protected_media = !empty($media->media) ? $media->media : '';

                $media->media = !empty($media->media) ? getSignUrl($media->media) : '';
                $media->cover = getSignUrl($media->cover);
                $media->username = isset($media->_user->name) ? $media->_user->name : (isset($media->name) ? $media->name : '');
                $media->avatar = isset($media->_user->avatar) ? getSignUrl($media->_user->avatar) : (isset($media->avatar) ? getSignUrl($media->avatar) : '');
                $media->is_star = ($user && $user->_mediaStars()->where('media_id',$media->id)->first()) ? 1 : 0;
                if ($user) {
                    $media_like = D('media_like')->where([ ['media_id', $media->id], ['uid', $user->id] ])->first();
                }
                $media->is_like = (isset($media_like) && $media_like->is_delete == '0') ? 1 : 0;

                $media->is_friend = 0;
                $media->is_attention = 0;

                // 登录状态，非自己
                if($is_login && $view_user_ticket->uid != $media->uid){
                    // 亲友
                    $friend_rows_id = FriendModel::getRowsObj([['uid', '=', $view_user_ticket->uid],['friend_uid', '=', $media->uid], ['status', '=', '1']], 'id');
                    // 关注好友状态
                    $friend_user_rows_id = FriendUser::getRowsObj([['uid', '=', $view_user_ticket->uid],['friend_id', '=', $media->uid], ['status', '=', '1'], ['type', '=', 3]], 'id');
                    if(!empty($friend_rows_id))
                        $media->is_friend = 1;
                    if(!empty($friend_user_rows_id))
                        $media->is_attention = 1;
                }
                if(isset($media->name)) unset($media->name);
                unset($media->_user);
            }

            unset($media);
        }else{
            EE('暂无数据', 0, 10157);
        }
    }

    /*
     * 浏览统计
     * */
    public static function addMediaHistory($media_id, $ticket)
    {
        MediaHistory::addMediaHistory($media_id, $ticket);
    }

    /*
     * 获取视频最新视频视频导演
     * */
    public static function getMediaDirector($uid)
    {
        $rows = Media::select(['player','director'])->where([['uid', '=', $uid], ['status', '=', 1], [ 'is_delete', '=', 0]])->orderBy('id', 'desc')->first();
        $arr = ['player'=>null, 'director'=>null];
        if(!empty($rows)){

            if(!empty($rows->player))
                $arr['player'] = json_decode($rows->player, true);
            if(!empty($rows->director))
                $arr['director'] = json_decode($rows->director, true);
        }
        return $arr;
    }

    /*
     * 用户最新视频
     * */
    public static function newest_media_rows($uid)
    {
        if(empty($uid))
            return [];

        $fields = ['id','title', 'description','media','comments','star','like','is_like','uid','created_at','address','location','cover','video_length','share','is_forward'];
        $user_latest_media = Media::where([['uid', '=', $uid], ['status', '=', 1], ['is_delete', 0], ['is_forward', '=', 0]])->with('users')->orderBy('id', 'desc')->first($fields);
        $tmep_arr = [];
        if (!empty($user_latest_media)) {
            $tmep_arr_data = $user_latest_media->toArray();

            $tmep_arr['id'] = $tmep_arr_data['id'];
            $tmep_arr['title'] = $tmep_arr_data['title'];
            $tmep_arr['description'] = $tmep_arr_data['description'];
            $tmep_arr['comments'] = $tmep_arr_data['comments'];
            $tmep_arr['star'] = $tmep_arr_data['star'];
            $tmep_arr['like'] = $tmep_arr_data['like'];
            $tmep_arr['is_like'] = $tmep_arr_data['is_like'];
            $tmep_arr['uid'] = $tmep_arr_data['uid'];
            $tmep_arr['created_at'] = $tmep_arr_data['created_at'];
            $tmep_arr['address'] = $tmep_arr_data['address'];
            $tmep_arr['location'] = $tmep_arr_data['location'];
            $tmep_arr['video_length'] = $tmep_arr_data['video_length'];
            $tmep_arr['share'] = $tmep_arr_data['share'];
            $tmep_arr['name'] = $tmep_arr_data['users']['name'];
            $tmep_arr['protected_avatar'] = !empty($tmep_arr_data['users']['avatar']) ? $tmep_arr_data['users']['avatar'] : '';
            $tmep_arr['protected_media'] = !empty($tmep_arr_data['media']) ? $tmep_arr_data['media'] : '';
            $tmep_arr['username'] = $tmep_arr_data['users']['name'];
            $tmep_arr['avatar'] = !empty($tmep_arr_data['users']['avatar']) ? $tmep_arr_data['users']['avatar'] : ''; // getSignUrl($tmep_arr_data['users']['avatar'])
            $tmep_arr['sex'] = $tmep_arr_data['users']['sex'];
            $tmep_arr['media'] = $tmep_arr_data['media'];//getSignUrl($tmep_arr_data['media']);
            $tmep_arr['cover'] = $tmep_arr_data['cover'];//getSignUrl($tmep_arr_data['cover']);
            $tmep_arr['is_forward'] = $tmep_arr_data['is_forward'];
            // 自己查看自己，不存在收藏和点赞，关注，亲友
            $tmep_arr['is_star'] = 0; // 是否收藏
            $tmep_arr['is_like'] = 0; // 是否点赞
            $tmep_arr['is_friend'] = 0; // 是否亲友
            $tmep_arr['is_attention'] = 0; // 是否关注
        }

        return $tmep_arr;
    }

    /*
     * 首页视频列表
     * */
    public static function getIndexMedia($request)
    {
        $type = $request->input('type');
        $page = intval($request->input('page')) ? intval($request->input('page')) :1;
        $page = $page - 1;
        $pageSize = config('admin.pageSize');
        $ticket = $request->input('ticket');

        // 是否登录
        $is_login = $user_ticket_data = checkTicket($ticket);
        $uid = empty($user_ticket_data) ? 0 : $user_ticket_data['uid'];

        // 获取个人发布最新视频，亲友圈、关注不显示个人的视频
        if (!empty($user_ticket_data) && ($page === 0) && ($type == 'recommend'))
            $user_latest_media = self::newest_media_rows($user_ticket_data['uid']);

        // 如果是第一页的最新和最热，要少查询一条
        if (isset($user_latest_media) && $user_latest_media && in_array($type, ['hot', 'recommend']))
            $pageSize = $pageSize - 1;

        // 处理第一页左滑
        if($page < 0) {
            $page = 0;
        }
        
        $media_list = [];
        switch ($type) {
            // 关注
            case 'follow':
                if ($is_login) {
                    $offset = $page * $pageSize;

                    $feild = 'm.`id`, m.`title`, m.`description`, m.`media`,m.`comments`,m.`star`,m.`like`,m.`is_like`,m.`uid`,m.`created_at`,m.`address`, m.`location`,m.`cover`,m.`video_length`,m.`share` ,u.avatar,u.name,m.is_forward,m.parent_id,m.remarks,is_screen_recording,u.sex';
                    $sql = "select {$feild} from media as m "
                    ." left join users as u"
                    ." on m.uid=u.id"
                    ." where m.status=1 and is_delete=0 and m.is_private=0 "
                    ." and (m.uid in (select friend_id from friend_user where uid={$user_ticket_data['uid']} and status=1 and type=3) ) "
                    ." ORDER BY m.`id` DESC LIMIT {$offset},{$pageSize}";

                    $media_list = DB::select($sql);
                }
                break;
            // 亲友圈
            case 'friend':
                if ($is_login) {
                    $offset = $page * $pageSize;

                    $feild = 'm.`id`, m.`title`,m.`description`, m.`media`,m.`comments`,m.`star`,m.`like`,m.`is_like`,m.`uid`,m.`created_at`,m.`address`,m.`location`,m.`cover`,m.`video_length`,m.`share` ,u.avatar,u.name,m.is_forward,m.parent_id,m.remarks,is_screen_recording,u.sex';
                    $sql = "select {$feild} from media as m "
                    ." left join users as u"
                    ." on m.uid=u.id"
                    ." where m.status=1 and is_delete=0 and m.is_private!=1 "
                    ." and (m.uid in (select uid from friend where friend_uid={$user_ticket_data['uid']} and status=1) ) " // m.uid in (select friend_uid as uid from friend where uid={$view_user_ticket->uid} and status=1) or
                    ." ORDER BY m.`id` DESC LIMIT {$offset},{$pageSize}";

                    $media_list = DB::select($sql);
                }
                break;
            // 推荐
            case 'recommend':
                $mobile_unique_code = IT('mobile_unique_code');
                $mobileMarkRows = MobileMark::getRowsArray([['mobile_unique_code', '=', $mobile_unique_code]]);
                $c = DB::connection('mysql2');

                $media_ids = '';
                if($is_login){
                    $media_ids = $c->table('recommend_list')->where('uid', $user_ticket_data['uid'])->value('vids');
                }else{
                    // 通过设备
                    if(!empty($mobileMarkRows)) {
                        $media_ids = $c->table('non_login_list')->where([['did', '=', $mobileMarkRows['id']]])->value('vids');
                    }
                }

                // 取默认推荐
                if(empty($media_ids)) {
                    $media_ids = $c->table('recommend_list')->where([['uid', '=', '0']])->value('vids');
                }

                $redis_recommend_did = !empty($mobileMarkRows) ? $mobileMarkRows['id'] : 0;
                $video_recommend_key = 'media_recommend_delete_vids_'.$redis_recommend_did.'-'. $uid;
                // 当查看第一页或者第一页左滑时，清空已看过的视频缓存
                if($page == 0) {
                    Redis::del($video_recommend_key);
                }
                $old_recommend_arr = [];
                if(!empty($media_ids)){
                    // 处理还没有写入filtr_recommend之前，算法系统重新生成新的推荐,上一页的数据又在下一页显示的重复问题
                    $old_recommend = Redis::get($video_recommend_key);
                    $media_ids_arr = explode(',', $media_ids);
                    if($old_recommend) {
                        $old_recommend_arr = explode(',', $old_recommend);
                        foreach($old_recommend_arr as $o_recommend) {
                            if(in_array($o_recommend, $media_ids_arr)) {
                                unset($media_ids_arr[array_search($o_recommend, $media_ids_arr)]);
                            }
                        }
                    }

                    $_media_ids = array_slice($media_ids_arr, 0, $pageSize);

                    if(!empty($_media_ids)){

                        $feild = 'm.`id`, m.`title`,m.`description`, m.`media`,m.`comments`,m.`star`,m.`like`,m.`is_like`,m.`uid`,m.`created_at`,m.`address`,m.`location`,m.`cover`,m.`video_length`,m.`share` ,u.avatar,u.name,m.is_forward,m.parent_id,m.remarks,is_screen_recording,u.sex';
                        $sql = "select ".$feild." from media as m left join users as u on m.uid=u.id where m.status=1 and m.is_delete=0 and m.is_private=0 and m.is_forward=0 

                        and m.id in (".implode(',', $_media_ids).") order by field (m.id,".implode(',', $_media_ids).")"; //

                        $media_list = DB::select($sql);

                    }
                }
                if(!empty($_media_ids) && !empty($_media_ids[0])){
                    // 已看过的视频写入缓存
                    $old_recommend_arr = array_merge($old_recommend_arr, $_media_ids);
                    if($old_recommend_arr) {
                        Redis::setex($video_recommend_key, 600, implode(',', $old_recommend_arr));
                    }
                    $did = (isset($mobileMarkRows['id']) && intval($mobileMarkRows['id']) > 0 ) ? $mobileMarkRows['id'] : 0;
                    // 存储list 列表
                    Redis::rPush('algorithm_log', json_encode(['type'=>'filtr_recommend', 'create_time'=>time(), 'data'=>['uid'=>$uid, 'did'=>$did, 'media_ids'=>implode(',', $_media_ids)]]));
                }
                break;
            default:
                $media_list = array();
                break;
        }

        $media_list_arr = [];
        if(isset($user_latest_media) && !empty($user_latest_media) && !empty($media_list)){
            // 个人最新视频向头部推送
            array_unshift($media_list, $user_latest_media);
        }else if(isset($user_latest_media) && !empty($user_latest_media)){
            $media_list[] = $user_latest_media;
        }
        $media_list_arr = self::Media_list_detail($media_list, $uid);
        return $media_list_arr;
    }

    /*
     * 视频详情 --数据格式化
     * */
    public static function Media_list_detail($media_list, $uid)
    {
        $temp_arr = [];
        $return_arr = [];
        $temp_arr_id = [];

        if(!empty($media_list)){
            foreach ($media_list as $key=>$value){
                if(is_object($value))
                    $value = object_to_array($value);
                if(!empty($temp_arr_id) && in_array($value['id'], $temp_arr_id))
                    continue;
                $temp_arr_id[] = $value['id'];

                // 初始化所有赋值
                unset($temp_arr);
                $value['forward_name'] = null;
                $value['forward_content'] = null;
                // 处理转发的视频
                if($value['is_forward'] == 1 && $value['parent_id'] != 0) {
                    $feild = 'm.`id`, m.`title`,m.`description`, m.`media`,m.`comments`,m.`star`,m.`like`,m.`is_like`,m.`uid`,m.`created_at`,m.`address`,m.`location`,m.`cover`,m.`video_length`,m.`share` ,u.avatar,u.name,u.sex';
                    $sql = "select {$feild} from media as m "
                        ." left join users as u"
                        ." on m.uid=u.id"
                        ." where m.status=1 and is_delete=0 and m.is_private!=1 and m.id =".$value['parent_id'];

                    $media_info = DB::select($sql);
                    if(empty($media_info)) {
                        continue;
                    }

                    $comment_content = $value['remarks'];
                    $name = $value['name'];
                    $is_forward = $value['is_forward'];
                    $value = object_to_array(array_pop($media_info));
                    $value['is_forward'] = $is_forward;
                    $value['forward_name'] = $name;
                    $value['forward_content'] = $comment_content;
                }
                $temp_arr = $value;
                $is_star = $is_like = 0;

                if($uid > 0){
                    // 是否收藏
                    $is_star = MediaStar::is_star_media($uid, $value['id']);
                    $is_like = MediaLike::is_like_media($uid, $value['id']);
                }

                $media_users_arr = User::get_user_rows_arr($value['uid']);
                $temp_arr['protected_avatar'] = isset($media_users_arr['avatar']) ? $media_users_arr['avatar'] : '';
                $temp_arr['protected_media'] = isset($value['media']) ? $value['media'] : '';
                $temp_arr['media'] = isset($value['media']) ? getSignUrl($value['media']) : '';
                $temp_arr['cover'] = getSignUrl($value['cover']);
                $temp_arr['username'] = isset($media_users_arr['name']) ? $media_users_arr['name'] : '';
                $temp_arr['avatar'] = isset($media_users_arr['avatar']) ? getSignUrl($media_users_arr['avatar']) : '';
                $temp_arr['is_star'] = $is_star ? 1 : 0;
                $temp_arr['is_like'] = $is_like ? 1 : 0;
                $temp_arr['is_friend'] = 0;
                $temp_arr['is_attention'] = 0;

                if($value['uid'] != $uid){
                    $is_friend = FriendModel::is_friend($uid, $value['uid']);
                    $is_attention = FriendUser::is_attention($uid, $value['uid']);
                    $temp_arr['is_friend'] = $is_friend ? 1 : 0;
                    $temp_arr['is_attention'] = $is_attention ? 1 : 0;
                }
                $return_arr[] = $temp_arr;
            }
        }
        return $return_arr;
    }

    /**
     * @desc 转发视频
     * @param $params
     * @return bool
     * @throws \Exception
     */
    public static function forwardingMedia($params)
    {
        if(empty($params['media_id']) || empty($params['uid'])) {
            EE('未知视频资讯', 0, 10100);
            return false;
        }
        if(!empty($params['content']) && mb_strlen($params['content']) > 30) {
            EE('转发的内容不能超过30个字符', 0, 10245);
            return false;
        }

        $media_info = Media::where(['id' => $params['media_id'], 'is_delete' => 0, 'status' => 1, 'is_forward' => 0])->first();
        if(empty($media_info)) {
            EE('想要转发的资讯不存在，无法转发', 0, 10246);
            return false;
        }
        if($media_info->is_private == 1) {
            EE('这是你私密收藏的影片，暂不支持转发哦', 0, 10250);
            return false;
        }
        if($media_info->is_private == 2) {
            if($media_info->uid == $params['uid']) {
                EE('这是你发布到亲友圈的影片，暂不支持转发哦', 0, 10251);
            } else {
                EE('该用户设置了权限，本影片无法转发', 0, 10252);
            }
            return false;
        }

        $filter_content = self::filter_comment_content($params['content']);

        DB::beginTransaction();

        // 添加转发评论
        $comment_data = [
            'uid' => $params['uid'],
            'reply_uid' => 0,
            'media_id' => $params['media_id'],
            'parent_id' => 0,
            'relation_id' => '',
            'content' => $filter_content,
            'type' => 1,
            'created_at' => time2date(),
            'updated_at' => time2date(),
        ];
        $comment_id = MediaComment::insertGetId($comment_data);
        if(!$comment_id) {
            DB::rollBack();
            EE('评论异常', 0, 10154);
        }

        // 累加评论次数
        $media = self::checkMedia($params['media_id']);
        if (!$media)
            EE('您想要评论的资讯不存在，无法评论', 0, 10152);
        elseif ($media->is_delete)
            EE('您想要评论的资讯已被删除，无法评论', 0, 10153);

        $media->comments = $media->comments + 1;
        $media->share = $media->share + 1;
        $count_rs = $media->save();
        if(!$count_rs) {
            DB::rollBack();
            EE('评论异常', 0, 10154);
        }

        $user_dynamic_data = [
            [
                'uid' => $media_info->uid,
                'type' => 3,
                'operation_id' => $comment_id,
                'parent_id' => 0,
                'option_uid' => $params['uid'],
                'media_id' => $media_info->id,
                'option_other' => $media_info->cover,
                'option_content' => $filter_content,
                'create_time' => time(),
                'update_time' => time()
            ],
        ];

        if($media_info->uid != $params['uid']) {
            $user_dynamic_data[] = [
                'uid' => $params['uid'],
                'type' => 3,
                'operation_id' => $comment_id,
                'parent_id' => 0,
                'option_uid' => $params['uid'],
                'media_id' => $media_info->id,
                'option_other' => $media_info->cover,
                'create_time' => time(),
                'update_time' => time(),
                'option_content' => $filter_content,
            ];
        }

        $dynamic_rs = UserDynamicList::insert($user_dynamic_data);
        if(!$dynamic_rs) {
            DB::rollBack();
            EE('添加动态异常', 0, 10155);
        }

        $media_data = [
            'uid' => $params['uid'],
            'title' => $media_info->title,
            'description' => $media_info->description,
            'media' => $media_info->media,
            'screenwriter' => $media_info->screenwriter,
            'staring' => $media_info->staring,
            'player' => $media_info->player,
            'director' => $media_info->director,
            'pv' => 0,
            'comments' => 0,
            'star' => 0,
            'sorts' => $media_info->sorts,
            'share' => 0,
            'like' => 0,
            'date' => $media_info->date,
            'location' => $media_info->location,
            'province' => $media_info->province,
            'city' => $media_info->city,
            'status' => $media_info->status,
            'created_at' => time2date(),
            'updated_at' => time2date(),
            'is_delete' => 0,
            'is_like' => 0,
            'address' => $media_info->address,
            'cover' => $media_info->cover,
            'video_length' => $media_info->video_length,
            'is_private' => $media_info->is_private,
            'is_owner' => $media_info->is_owner,
            'tags' => $media_info->tags,
            'reports_number' => 0,
            'parent_id' => $params['media_id'],
            'forward_id' => $comment_id,
            'is_forward' => 1,
            'remarks' => $params['content'],
        ];

        $media_rs = Media::insert($media_data);
        if(!$media_rs) {
            DB::rollBack();
            return false;
        }

        DB::commit();

        // 推送--队列 --对视频发布者推送
        $_user = D('users')->find($media_info->uid);

        //////////////////////////////////////////////////////////////////////////
        // 关注推送
        $attentionUserList = FriendUser::where([['friend_id', '=', $params['uid']], ['status', '=', '1']])->with('user')->get();
        if ($attentionUserList) {
            // 遍历推送
            foreach ($attentionUserList as $value) {
                if (!empty($value->user->registration_id)) {
                    $registration_id = $value->user->registration_id;
                    $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $registration_id]]);
                    // 消息推送
                    if(!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])){

                        ////////////////////////////////////////////////////////////////////////////////////////////////
                        $data = [];
                        $push_channel_key = 'jpush';
                        if($getPushChannel['push_channel_id'] == 2){
                            $push_channel_key = 'hpush';
                        }else if($getPushChannel['push_channel_id'] == 3){
                            $push_channel_key = 'xmpush';
                        }

                        // 标题  --app 通过notify id 0处理业务 --透传
                        $data['channel_id'] = $getPushChannel['push_channel_id'];
                        $data['title'] = trans('notice.10259');//'您关注的用户发布了新视频'; // 登录标题
                        $data['content'] = trans('notice.10259');// 内容
                        $data['description'] = trans('notice.10259'); // 描述
                        $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                        $data['notify_id'] = 0;     // 通知id   --app 处理业务标识
                        $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                        $data['mobile_list'] = $getPushChannel['registration_id'];
                        // $data['mobile_unique_code'] = IT('mobile_unique_code');
                        dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));

                        // 保留原始功能
                        if($push_channel_key == 'jpush'){
                            // 发通知提示用户   --通知
                            unset($data['msg_type']);
                            $data['msg_type'] = config('push')[$push_channel_key]['type']['notify'];  // 消息类型：1通知 0透传
                            dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                        }
                        ////////////////////////////////////////////////////////////////////////////////////////////////
                    }
                }
            }
        }

        // 亲友圈推送
        $friendList = FriendModel::where([['friend_uid', '=', $params['uid']], ['status', '=', '1']])->with('user')->get();
        if(!empty($friendList)){
            foreach ($friendList as $value){
                if(!empty($value->user->registration_id)){
                    $registration_id = $value->user->registration_id;
                    if ($registration_id) {

                        $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $registration_id]]);
                        // 消息推送
                        if(!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])){

                            ////////////////////////////////////////////////////////////////////////////////////////////////
                            $data = [];
                            $push_channel_key = 'jpush';
                            if($getPushChannel['push_channel_id'] == 2){
                                $push_channel_key = 'hpush';
                            }else if($getPushChannel['push_channel_id'] == 3){
                                $push_channel_key = 'xmpush';
                            }

                            // 标题  --app 通过notify id 0处理业务 --透传
                            $data['channel_id'] = $getPushChannel['push_channel_id'];
                            $data['title'] = trans('notice.10260'); // 登录标题
                            $data['content'] = trans('notice.10260');// 内容
                            $data['description'] = trans('notice.10260'); // 描述
                            $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                            $data['notify_id'] = 1;     // 通知id   --app 处理业务标识
                            $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                            $data['mobile_list'] = $getPushChannel['registration_id'];
                            // $data['mobile_unique_code'] = IT('mobile_unique_code');
                            dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));

                            // 保留原始功能
                            if($push_channel_key == 'jpush'){
                                // 发通知提示用户   --通知
                                unset($data['msg_type']);
                                $data['msg_type'] = config('push')[$push_channel_key]['type']['notify'];  // 消息类型：1通知 0透传
                                dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                            }
                            ////////////////////////////////////////////////////////////////////////////////////////////////
                        }
                    }
                }
            }
        }

        if ($_user && $_user->registration_id){

            $getPushChannel = JpushMobile::getRowsArray([['registration_id', '=', $_user->registration_id]]);
            // 消息推送
            if(!empty($getPushChannel) && !empty($getPushChannel['push_channel_id'])){
                $notifyContent = trans('notice.10213'); // 其他用户转发了您发布的视频';

                ////////////////////////////////////////////////////////////////////////////////////////////////
                // 标题  --app 通过notify id 0处理业务 --透传
                $data = [];
                $push_channel_key = 'jpush';
                if($getPushChannel['push_channel_id'] == 2){
                    $push_channel_key = 'hpush';
                }else if($getPushChannel['push_channel_id'] == 3){
                    $push_channel_key = 'xmpush';
                }

                $data['channel_id'] = $getPushChannel['push_channel_id'];
                $data['title'] = trans('notice.10249');//'转发'; // 登录标题
                $data['content'] = $notifyContent;// 内容
                $data['description'] = $notifyContent; // 描述
                $data['msg_type'] = config('push')[$push_channel_key]['type']['ospf'];  // 消息类型：1通知 0透传
                $data['notify_id'] = 2;     // 通知id   --app 处理业务标识
                $data['notify_foreground'] = 0; // 开启/关闭app在前台时的通知弹出 1:弹出通知  0 不弹出
                $data['mobile_list'] = $getPushChannel['registration_id'];
                $data['mobile_unique_code'] = IT('mobile_unique_code');
                dispatch((new PushQueue(['type'=>'singlePush', 'data'=>$data]))->onQueue('push'));
                ////////////////////////////////////////////////////////////////////////////////////////////////
            }
        }
        return true;
    }

    /**
     * @desc 敏感词过滤
     * @param $content
     * @return string
     */
    private static function filter_comment_content($content) {
        $interference = ['&', '*'];
        $filename = config_path().'/sensitiveword.txt'; //每个敏感词独占一行
        Sensitive::interference($interference); //添加干扰因子
        Sensitive::addwords($filename); //需要过滤的敏感词
        $filter_content = Sensitive::filter($content);
        $filter_content = Filter::init($filter_content);

        return $filter_content;
    }

    /*
     * 初始化点赞统计
     * */
    public static function init_media_like_static($uid)
    {
        if(empty($uid))
            return false;

        // 点赞任务
        $activity_confit_rows = ActivityConfig::where([['activity_type', '=', 2]])->orderBy('id', 'desc')->first();
        if(empty($activity_confit_rows))
            return false;
        // 活动状态
        if($activity_confit_rows->status != 1)
            return false;
        if($activity_confit_rows->start_time > time())
            return false;
        if($activity_confit_rows->end_time < time())
            return false;

        // 当前周数据是否存在
        $media_like_static_rows = MediaLikeStatic::where([['type', '=', 1], ['date_format', '=', date("W", time())], ['uid', '=', $uid]])->first();
        if(empty($media_like_static_rows)){
            unset($model);
            $model = new MediaLikeStatic();
            $model->activity_id = $activity_confit_rows->id;
            $model->type = 1;
            $model->date_format = date("W", time());
            $model->uid = $uid;
            $model->create_time = time();
            $model->update_time = time();
            $model->save();
        }

        // 当前月数据是否存在
        $media_like_static_rows = MediaLikeStatic::where([['type', '=', 2], ['date_format', '=', date("Ym", time())], ['uid', '=', $uid]])->first();
        if(empty($media_like_static_rows)){
            unset($model);
            $model = new MediaLikeStatic();
            $model->activity_id = $activity_confit_rows->id;
            $model->type = 2;
            $model->date_format = date("Ym", time());
            $model->uid = $uid;
            $model->create_time = time();
            $model->update_time = time();
            $model->save();
        }
        return true;
    }

    /*
     * 删除视频
     * 删除本周、本月排行
     * */
    public static function change_ranking($media_id)
    {
        $media_rows = Media::where([['id', '=', $media_id]])->first();
        if($media_rows->is_participate_activity != 1 )
            return true;
        $media_uid = $media_rows->uid;

        $week_date = date("W", time());
        $month_date = date("Ym", time());
        $month_start = mktime(0,0,0,date('m'),1,date('Y'));
        $month_end = mktime(23,59,59,date('m'),date('t'),date('Y'));
        // 周的起始时间和周结束时间
        $week_data = weekday(date("Y", time()), (date("W", time())));

        $media_like_static_model = new MediaLikeStatic();

        DB::beginTransaction();
        try{
            // 本周点赞数量     删除本周排行的数据
            $where[] = ['media_id', '=', $media_id];
            $where[] = ['type', '=', 1];
            $where[] = ['create_time', '>=', $week_data['start']];
            $where[] = ['create_time', '<=', $week_data['end']];

            $month_media_like_num = $week_media_like_num = MediaLikeLog::where($where)->count();
            if($week_media_like_num > 0){
                $week_static_rows = $media_like_static_model->select('like_num')->where([['uid', '=', $media_uid], ['date_format', '=', $week_date]])->first();
                if(!empty($week_static_rows)){
                    $update_num = ($week_static_rows->like_num > $week_media_like_num) ? $week_media_like_num : $week_static_rows->like_num;
                    $update_sql = "update ".$media_like_static_model->getTable()." set like_num=like_num-".$update_num.", update_time=".time().", status=2 where uid={$media_uid} and date_format={$week_date} and status=0";
                    $update_result = DB::update($update_sql);
                    if(!$update_result)
                        throw new \Exception('更新周排行数据异常');
                }
            }

            // 本月点赞数量     删除本月排行的数据
            unset($where);
            $where[] = ['media_id', '=', $media_id];
            $where[] = ['type', '=', 1];
            $where[] = ['create_time', '>=', $month_start];
            $where[] = ['create_time', '<=', $month_end];
            if($month_media_like_num > 0){
                $month_static_rows = $media_like_static_model->select('like_num')->where([['uid', '=', $media_uid], ['date_format', '=', $month_date]])->first();
                if(!empty($month_static_rows)){
                    $update_num = ($month_static_rows->like_num > $week_media_like_num) ? $month_media_like_num : $month_static_rows->like_num;
                    $update_sql = "update ".$media_like_static_model->getTable()." set like_num=like_num-".$update_num.", update_time=".time().", status=2 where uid={$media_uid} and date_format={$month_date} and status=0";
                    $update_result = DB::update($update_sql);
                    if(!$update_result)
                        throw new \Exception('更新周排行数据异常');
                }
            }

            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();

            // 处理异常,写入Mongodb
            $params = [['type' => 'del_media', 'status' => 'error', 'params'=> json_encode(['media_uid'=>$media_uid, 'media_id'=>$media_id]), 'content' => $e->getMessage(), 'created_at' => time2date()]];
            insert_mongodb_log(config('feild.type.monitoring.1.id'), $params);
            return false;
        }
    }

    /*
     * 视频排序
     * */
    public function media_sort()
    {
        $list = MediaRecommend::select(['id', 'sort', 'media_id'])->where([['status', '=', 1]])->orderby('sort', 'asc')->get();

        if(!empty($list)){
            $i=0;
            foreach ($list as $key=>$value) {
                $i++;
                $update = MediaRecommend::where([['id', '=', $value->id]])->update(['sort'=>$i]);
            }
        }
        return ['status'=>'success', 'message'=>'排序成功', 'data'=>[]];
    }

    /*
     * 删除推荐
     * */
    public function del_recommend($media_id)
    {
        try{
            $rows = MediaRecommend::where([['media_id', '=', $media_id]])->first();
            if(empty($rows))
                throw new \Exception("不存在推荐视频");
            $result = MediaRecommend::where([['id', '=', $rows->id]])->delete();
            if(!$result)
                throw new \Exception("删除失败");
            self::media_sort();
            return ['status'=>'error', 'message'=>'删除成功', 'data'=>[]];
        }catch (\Exception $e) {
            return ['status'=>'error', 'message'=>$e->getMessage(), 'data'=>[]];
        }
    }

}

